package com.tz.colawallet.basecode.base;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.trello.rxlifecycle.components.support.RxFragmentActivity;
import com.tz.colawallet.R;
import com.tz.colawallet.basecode.util.ToastUtil;
import com.tz.colawallet.bean.MessageEvent;
import com.umeng.analytics.MobclickAgent;
import com.wang.avi.AVLoadingIndicatorView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by JINAN on 2017/10/12.
 */

public abstract class BaseActivity extends RxFragmentActivity {
    private static boolean isMobleConnect, isWifiConnect;
    //两次点击时间间隔
    public static final int TIME_INTERVAL = 500;
    private boolean mIsCurrentNetworkConnected = true;
    private AVLoadingIndicatorView avLoadingView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResId());
        bind();
        setup();
        initTitle();
        init();
    }

    /**
     * @return 布局id
     */
    protected abstract int getLayoutResId();

    /**
     * 初始化view以及数据
     */
    protected abstract void init();

    /**
     * 初始化标题
     */
    protected abstract void initTitle();

    protected void bind() {
        EventBus.getDefault().register(this);
        registerReceiver();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {/* Do something */}

    /**
     * 依赖注入
     */
    protected void setup() {
    }

    /**
     * 硬体返回键
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            //防止连续点击打开多个界面
            if (isFastDoubleClick()) {
                return true;
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }


    /**
     * 隐藏输入框
     *
     * @param v
     * @param event
     * @return
     */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是快速点击
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < TIME_INTERVAL) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        if (null != mReceiver) {
            registerReceiver(mReceiver, filter);
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
                boolean connected = isNetworkConnected();
                //断开
                if (mIsCurrentNetworkConnected) {
                    if (!connected) {
                        showNetworkConnection(false);
                    }
                } else {    //连接
                    if (connected) {
                        showNetworkConnection(true);
                        onConnectRefresh();
                    }
                }
                mIsCurrentNetworkConnected = connected;
            }
        }
    };

    protected void onConnectRefresh() {
        //网络连接时，刷新页面
    }

    protected boolean isNetworkConnected() {
        return isNetworkConnected(this);
    }


    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (mConnectivityManager != null) {
                NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
                if (mNetworkInfo != null) {
                    return mNetworkInfo.isAvailable();
                }
            }
        }
        return false;
    }

    private static void netWorkSwitch(boolean mobileInfo, boolean wifiInfo) {
        //数据---WIFI
        if (isMobleConnect && !isWifiConnect) {
            //移动网络开启时，wifi连接上
            if (mobileInfo && wifiInfo) {

            }
            isMobleConnect = mobileInfo;
            isWifiConnect = wifiInfo;
        }
    }

    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    protected boolean showNetworkConnection(boolean isConnected) {
        showToast(isConnected ? R.string.network_connected : R.string.network_disconnected);
        return false;
    }
//    protected void  setTitleBar(String color){
//        UltimateBar ultimateBar = new UltimateBar(this);
//        ultimateBar.setColorBar(Color.parseColor(color), false);
//    }


//    protected void setToolBar(@StringRes int res, String color) {
//        toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
//        ActionBar actionBar = getSupportActionBar();
//        if (actionBar != null) {
//            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
//        }
//        if(!StringUtils.isEmpty(color)){
//            toolbar.setBackgroundColor(Color.parseColor(color));
//        }
//        TextView title = (TextView) toolbar.findViewById(R.id.title);
//        FrameLayout back = (FrameLayout) toolbar.findViewById(R.id.back);
//        RxView.clicks(back)
//                .compose(this.<Void>bindToLifecycle())
//                .throttleFirst(500, TimeUnit.MILLISECONDS)
//                .subscribe(new Action1<Void>() {
//                    @Override
//                    public void call(Void aVoid) {
//                        finishAct();
//                    }
//                });
//        title.setText(res);
//    }

//    protected void setToolBar(String str, String color) {
//        toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
//        ActionBar actionBar = getSupportActionBar();
//        if (actionBar != null) {
//            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
//        }
//        if(!StringUtils.isEmpty(color)){
//            toolbar.setBackgroundColor(Color.parseColor(color));
//        }
//        TextView title = (TextView) toolbar.findViewById(R.id.title);
//        FrameLayout back = (FrameLayout) toolbar.findViewById(R.id.back);
//        RxView.clicks(back)
//                .compose(this.<Void>bindToLifecycle())
//                .throttleFirst(500, TimeUnit.MILLISECONDS)
//                .subscribe(new Action1<Void>() {
//                    @Override
//                    public void call(Void aVoid) {
//                        finishAct();
//                    }
//                });
//        title.setText(str);
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (null != mReceiver) {
            unregisterReceiver(mReceiver);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    /**
     * 网络出错处理
     *
     * @param event
     */
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onNetErrorEvent(NetErrorEvent event) {
//        if (event.getLevel() > 0) { // 重连策略
//            if (retryCount < 3) { // 限制3次
//                onNetError(event);
//                retryCount++;
//            } else {
//                loading(false);
//                retryCount = 0;
//            }
//        } else {
//            loading(false);
//        }
//    }

//    protected abstract void onNetError(NetErrorEvent event);

    /**
     * 302跳转登录
     */
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onLoginEvent(LoginEvent event) {
//
//    }
    protected void showToast(int resId) {
        ToastUtil.showText(this, resId);
    }

    protected void showToast(String msg) {
        ToastUtil.showText(this, msg);
    }

    protected void switchActivity(Class<?> cls, Bundle extras) {
        Intent intent = new Intent(this, cls);
        if (extras != null) {
            intent.putExtras(extras);
        }
        startActivity(intent);
    }

    protected void switchActivity(Class<?> cls, Bundle extras, int flags) {
        Intent intent = new Intent(this, cls);
        if (extras != null) {
            intent.putExtras(extras);
        }
        intent.setFlags(flags);
        startActivity(intent);
    }

    protected void switchActivityAndFinish(Class<?> cls, Bundle extras) {
        switchActivity(cls, extras);
        finish();
    }

    protected void switchActivityAndFinish(Class<?> cls, Bundle extras, int flags) {
        switchActivity(cls, extras, flags);
        finish();
    }

    protected void switchActivityForResult(Class<?> cls, int requestCode,
                                           Bundle extras) {
        Intent intent = new Intent(this, cls);
        if (extras != null) {
            intent.putExtras(extras);
        }
        startActivityForResult(intent, requestCode);
    }

    protected void switchActivityForResult(Class<?> cls, int requestCode,
                                           Bundle extras, int flags) {
        Intent intent = new Intent(this, cls);
        if (extras != null) {
            intent.putExtras(extras);
        }
        intent.setFlags(flags);
        startActivityForResult(intent, requestCode);

    }

    protected void finishActivityForResult() {
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
        finish();
    }

    protected void finishActivityWithExtra(Bundle extras) {
        Intent intent = new Intent();
        if (extras != null) {
            intent.putExtras(extras);
        }
        setResult(RESULT_OK, intent);
        finish();
    }

    protected void switchActivityReorder2Front(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);
    }

    protected void switchFragment(Fragment fragment, int resId, Bundle extras) {
        if (extras != null) {
            fragment.setArguments(extras);
            getSupportFragmentManager().beginTransaction()
                    .replace(resId, fragment).commit();
        }
    }

    public void loading(boolean isLoading) {
        if (isLoading) {
            View loadingView = getLayoutInflater().inflate(R.layout.item_loading, null);
            avLoadingView = loadingView.findViewById(R.id.av_loading_view);
            if (avLoadingView == null) {
                avLoadingView.show();
            }
            if (!avLoadingView.isShown()) {
                avLoadingView.show();
            }
        } else {
            if (avLoadingView != null && avLoadingView.isShown()) {
                avLoadingView.hide();
            }
        }
    }

    public void showMsg(String msg) {
        showToast(msg);
    }

}
